package com.imooc.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.dao.ProductMapper;
import com.imooc.mall.model.pojo.Product;
import com.imooc.mall.model.request.AddProductReq;
import com.imooc.mall.model.request.ProductListReq;
import com.imooc.mall.model.query.productListQuery;
import com.imooc.mall.service.CategoryService;
import com.imooc.mall.service.ProduceService;
import com.imooc.mall.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProduceServiceImpl implements ProduceService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryService categoryService;

    /**
     * 实现新增商品服务
     */

    @Override
    public void addProduct(AddProductReq addProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq,product);
        //判断当前名字是否已经存在
        Product productOld = productMapper.seletctByName(addProductReq.getName());
        if (productOld!=null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NEED_ADMIN.NAME_EXISTED);
        }
        //校验通过，进行添加·1
        int i = productMapper.insertSelective(product);
        if (i==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.CREATE_FAILED);
        }
    }

    /**
     * 文件上传
     */
    @Override
    public void upload(HttpServletRequest httpServletRequest,
                       @RequestParam("file") MultipartFile file){


    }


    /**
     * URL获取
     */
    @Override
    public URI getHost(URI uri){
        URI effectiveURI;
        try {
            effectiveURI= new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(),uri.getPort(),null,null,null);
        } catch (URISyntaxException e) {
            effectiveURI=null;
        }
        return effectiveURI;

    }

    /**
     * 修改商品的功能
     */
    @Override
    public void update(Product updateProduct){
        //现获取这个对象的信息
        Product productOld = productMapper.seletctByName(updateProduct.getName());
        if (productOld!=null && !updateProduct.getId().equals(productOld.getId())){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
        //调用修改
        int count = productMapper.updateByPrimaryKeySelective(updateProduct);
        if (count==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }
    /**
     * 删除商品
     */
    @Override
    public void deleteProductById(Integer id){
        //先判断这个id是否存在
        Product productOld = productMapper.selectByPrimaryKey(id);
        if (productOld==null){
            throw new ImoocMallException(ImoocMallExceptionEnum.DELETE_FAILED);
        }

        //验证完成，调用删除功能
        int count = productMapper.deleteByPrimaryKey(id);
        if (count==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.DELETE_FAILED);
        }
    }

    /**
     * 商品统一上下架功能
     */
    @Override
    public void bathUpdateSellStatus(Integer[] ids,
                                     Integer sellStatus){
        productMapper.bathUpdateSellStatus(ids,sellStatus);
    }

    /**
     * 后台商品展示方法
     */
    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        //进行商品查询
        List<Product> productList = productMapper.listForAdmin();
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;
    }

    /**
     * 前台查看商品详情
     */
    @Override
    public Product detail(Integer id){
        Product product = productMapper.selectByPrimaryKey(id);
        if (product==null){
            throw new ImoocMallException(ImoocMallExceptionEnum.SELECT_FAILED);
        }
        return product;

    }


    /**
     * 查询商品详情功能
     */
    @Override
    public PageInfo list(ProductListReq productListReq){

        productListQuery productListQuery = new productListQuery();
        //搜索处理
        if (!StringUtils.isEmpty(productListReq.getKeyword())){
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }

        //目录处理，如果查询的是某个目录下的商品，不仅要查出该目录下的，还要把所有子目录的商品都查出来
        //所以要拿到一个list集合
        if (productListReq.getCategoryId()!=null){
            List<CategoryVo> categoryVosList = categoryService.listCategoryForCustomer(productListReq.getCategoryId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVosList,categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }

        //排序处理
        String orderyBy = productListReq.getOrderyBy();
        if (Constant.productListOrderBy.PRICE_ASC_DESC.contains(orderyBy)){
            PageHelper.startPage(productListReq.getPageNum(),productListReq.getPageSize(),orderyBy);
        }else {
            PageHelper.startPage(productListReq.getPageNum(),productListReq.getPageSize());
        }

        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;
    }

    private void getCategoryIds(List<CategoryVo> categoryVosList,
                                ArrayList<Integer> categoryIds ){

        for (int i = 0; i < categoryVosList.size(); i++) {
            CategoryVo categoryVo =  categoryVosList.get(i);
            if (categoryVo!=null){
                categoryIds.add(categoryVo.getId());
                getCategoryIds(categoryVo.getChildrenCategory(),categoryIds);
            }

        }

    }


}
